/*
    Bandleader
    Copyright (c) 2006 by Grant Yoshida

    Licensed under the GPL version 2 or later,
    please see COPYING for details.
*/

#include "Cursor.h"
//
#include "CursorHost.h"


Cursor::Cursor(CursorHost *host) :
    QObject(),
    m_host(host),
    m_row(0),
    m_col(0)
{
}

void Cursor::moveUp()
{
    if (canMoveUp()) {
        --m_row;
        cursorMoved();
    }
}

void Cursor::moveDown()
{
    if (canMoveDown()) {
        ++m_row;
        cursorMoved();
    }
}

void Cursor::moveLeft()
{
    if (m_col > 0) {
        --m_col;
        cursorMoved();
    }
    else
        if (m_row > 0) {
            m_col = numCols()-1;
            --m_row;
            cursorMoved();
        }
}

void Cursor::moveRight()
{
    if (m_col < numCols()-1) {
        ++m_col;
        cursorMoved();
    }
    else
        if (m_row < numRows()-1) {
            m_col = 0;
            ++m_row;
            cursorMoved();
        }
}

void Cursor::setPos(int row, int col)
{
    if (row >= 0 && row < numRows() &&
        col >=0 && col < numCols()) {

        if (row != m_row || col != m_col) {
            m_row = row;
            m_col = col;
            cursorMoved();
        }
    }
}

bool Cursor::canMoveUp() const
{
    return m_row > 0;
}

bool Cursor::canMoveDown() const
{
    return m_row < numRows()-1;
}

bool Cursor::canMoveLeft() const
{
    return m_col > 0 || m_row > 0;
}

bool Cursor::canMoveRight() const
{
    return m_col < numCols()-1 ||
           m_row < numRows()-1;
}

int Cursor::index() const
{
    return m_row * numCols() + m_col;
}

int Cursor::numRows() const
{
    return m_host ? m_host->numRows() : 0;
}

int Cursor::numCols() const
{
    return m_host ? m_host->numCols() : 0;
}
